/*
 * Copyright 2015-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package signHelper.mvc;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 抽象，未用到
 * @author <a href="mailto:1360527082@qq.com">王焕</a>
 * @since 0.1.0
 */

public abstract class AbstractApiController {
	protected final Logger logger = LogManager.getLogger(getClass());
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Map<String, Object> handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
		logger.warn("api异常: {}", request.getRequestURI(), ex);
		ApiError error = ex instanceof ApiException ? ((ApiException) ex).getError() : new ApiError(ex);
		
		Integer httpCode = error.getHttpCode();
		response.setStatus(httpCode == null ? 500 : error.getHttpCode());
		Map<String, Object> result = new LinkedHashMap<>();
		result.put("_error", error.getValues());
		return result;
	}
}
